Array.prototype.mergeSort = function () {
  const rec = (arr) => {
    if (arr.length === 1) return arr; // 获取分过程中单个的数组
    const mid = Math.floor(arr.length / 2);
    const left = arr.slice(0, mid);
    const right = arr.slice(mid, arr.length);
    const leftOrder = rec(left);
    const rightOrder = rec(right);
    const res = [];
    while (leftOrder.length || rightOrder.length) {
      if (leftOrder.length && rightOrder.length) {
        res.push(
          leftOrder[0] < rightOrder[0] ? leftOrder.shift() : rightOrder.shift()
        );
      } else if (leftOrder.length) {
        res.push(leftOrder.shift());
      } else if (rightOrder.length) {
        res.push(rightOrder.shift());
      }
    }
    return res;
  };

  const res = rec(this);
  res.forEach((item, index) => {
    this[index] = item;
  });
};

const arr = [5, 4, 3, 2, 1];
arr.mergeSort(arr);
console.log(arr);
